﻿#if true

using System.Collections.Generic;
using System.Diagnostics;
using CxExtension;
using UnityEngine.Profiling;
using Debug = UnityEngine.Debug;

namespace UnityEngineExt
{
	internal class WatchInfo
	{
		public string name = "";//
		public long minLogTime = 0;
		private bool mAddProfiler;                      //
		public Stopwatch watch = new Stopwatch();

		public void Start(string text, long minLogTime = 15, bool addProfiler = true)
		{
			name = text;
			this.minLogTime = minLogTime;
			watch.Reset();
			watch.Start();
			mAddProfiler = addProfiler;
			if (addProfiler)
			{
				Profiler.BeginSample(name);
			}
		}

		public long Stop()
		{
			if (mAddProfiler)
			{

				Profiler.EndSample();
			}
			watch.Stop();
			var cost = watch.ElapsedMilliseconds;
			if (cost > minLogTime)
			{
				Debug.LogFormat("{0} cost:{1} ms\n{2:f3} s  {3}", name,cost, cost / 1000f, watch.Elapsed.ToString());
			}

			return cost;
		}
	}
	/// <summary>
	/// 性能分析接口,
	/// 仅仅用于主线程
	/// </summary>
	public static class ProfilerF
	{
		private static readonly ObjectPool<WatchInfo> mPool = new ObjectPool<WatchInfo>();                      //

		private static readonly Stack<WatchInfo> sStack = new Stack<WatchInfo>(10);
		private const long mDefaultMinLogTime = 500; //
		public static void BeginSample(string text)
		{
			BeginSample_(text, mDefaultMinLogTime, true);
		}
		public static void BeginSample(string text, bool addProfiler)
		{
			BeginSample_(text,mDefaultMinLogTime,addProfiler);
		}

		public static void BeginSample(string text, long minLogTime)
		{
			BeginSample_(text, minLogTime, true);
		}

		/// <summary>
		/// 开始性能采样,
		/// </summary>
		/// <param name="text">用于输出日志的前缀文本</param>
		/// <param name="minLogTime">触发日志打印的最小时间,单位 毫秒</param>
		/// <param name="addProfiler"></param>
		public static void BeginSample(string text, long minLogTime, bool addProfiler)
		{
			BeginSample_(text, minLogTime, addProfiler);
		}
		[Conditional("DEBUG")]
		public static void BeginSample_(string text, long minLogTime, bool addProfiler)
		{
			var watch = mPool.Get();
			sStack.Push(watch);
			watch.name = text;
			watch.Start(text, minLogTime);
		}
		
		public static long EndSample()
		{
			return EndSample_();
		}
		public static long EndSample_()
		{
#if DEBUG
			var watch = sStack.Pop();
			var cost = watch.Stop();
			mPool.Recycle(watch);
			return cost;
#else
			return 0;
#endif
		}


	}
}

#endif